package com.jinly.ryder.jenkins.service.impl;

import com.jinly.ryder.common.service.SystemSettingService;
import com.jinly.ryder.common.service.model.setting.JenkinsSetting;
import com.jinly.ryder.jenkins.service.JenkinsHttpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class JenkinsHttpServiceImpl implements JenkinsHttpService, InitializingBean {
    private final SystemSettingService systemSettingService;
    private RestTemplate restTemplate;

    @Override
    public String doGet(String path) {
        JenkinsSetting jenkinsSetting = systemSettingService.getSettingItem(JenkinsSetting.class);
        String url = jenkinsSetting.getUrl() + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(jenkinsSetting.getUsername(), jenkinsSetting.getPassword());
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        try {
            ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            if (resEntity.getStatusCode().is2xxSuccessful()) {
                return resEntity.getBody();
            } else if (resEntity.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                return null;
            } else {
                log.error("err:{}", resEntity);
                throw new RuntimeException("请求失败：" + resEntity.getStatusCode());
            }
        } catch (Exception e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException httpClientErrorException = (HttpClientErrorException) e;
                if (httpClientErrorException.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                    return null;
                }
            }
            log.error("err:{}", url, e);
            throw new RuntimeException("请求失败：" + e.getMessage());
        }
    }

    @Override
    public byte[] doGetDownLoad(String url) {
        HttpHeaders headers = new HttpHeaders();
        JenkinsSetting jenkinsSetting = systemSettingService.getSettingItem(JenkinsSetting.class);
        headers.setBasicAuth(jenkinsSetting.getUsername(), jenkinsSetting.getPassword());
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<byte[]> resEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, byte[].class);
        if (resEntity.getStatusCode().is2xxSuccessful()) {
            return resEntity.getBody();
        } else {
            log.error("err:{}", resEntity);
            throw new RuntimeException("请求失败：" + resEntity.getStatusCode());
        }
    }

    @Override
    public ResponseEntity<String> doPost(String path, Map<String, Object> param) {
        JenkinsSetting jenkinsSetting = systemSettingService.getSettingItem(JenkinsSetting.class);
        String url = jenkinsSetting.getUrl() + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(jenkinsSetting.getUsername(), jenkinsSetting.getPassword());
//        headers.setContentType(new MediaType("application", "xml", StandardCharsets.UTF_8));
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> resEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        if (!resEntity.getStatusCode().is2xxSuccessful()) {
            log.error("err:{}", resEntity);
            throw new RuntimeException("请求失败：" + resEntity.getStatusCode());
        }
        return resEntity;
    }

    @Override
    public void doPostXml(String path, String configXml) {
        JenkinsSetting jenkinsSetting = systemSettingService.getSettingItem(JenkinsSetting.class);
        String url = jenkinsSetting.getUrl() + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(jenkinsSetting.getUsername(), jenkinsSetting.getPassword());
        headers.setContentType(new MediaType("application", "xml", StandardCharsets.UTF_8));
        HttpEntity<String> requestEntity = new HttpEntity<>(configXml, headers);
        ResponseEntity<String> resEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        if (!resEntity.getStatusCode().is2xxSuccessful()) {
            log.error("err:{}", resEntity);
            throw new RuntimeException("请求失败：" + resEntity.getStatusCode());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5 * 1000);
        factory.setReadTimeout(5 * 1000);
        restTemplate = new RestTemplate(factory);
    }
}
